package socket.homework1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author lhn
 * @date 2024-04-26 15:53
 * 服务端
 */

public class Homework01Server {
    public static void main(String[] args) throws IOException {
        //创建一个 serverSocket 对象
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端socket等待连接...");
        Socket socket = serverSocket.accept();

        //获取通道中的输入流
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream)
        );

        //获取通道中的输出流
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(outputStream)
        );

        String str = bufferedReader.readLine();
        System.out.println("收到客户端消息");
        String msg = "";
        switch (str) {
            case "name":
                msg = "我是nova";
                break;
            case "hobby":
                msg = "编写Java程序";
                break;
            default:
                msg = "你说啥呢";
                break;
        }
        bufferedWriter.write(msg);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        System.out.println("发送消息给客户端");

        //释放资源
        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();
    }
}
